package com.cskaoyan.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.cskaoyan.mall.commons.exception.ValidateException;
import com.cskaoyan.user.constants.UserRetCode;
import com.cskaoyan.user.converter.MemberConverter;
import com.cskaoyan.user.dal.entitys.Member;
import com.cskaoyan.user.dal.entitys.UserVerify;
import com.cskaoyan.user.dal.persistence.MemberMapper;
import com.cskaoyan.user.dal.persistence.UserRegisterMapper;
import com.cskaoyan.user.dal.persistence.UserVerifyMapper;
import com.cskaoyan.user.dto.UserRegisterRequest;
import com.cskaoyan.user.dto.UserRegisterResponse;
import com.cskaoyan.user.service.IRegisterService;
import com.cskaoyan.user.utils.ExceptionProcessorUtils;
import jodd.util.CollectionUtil;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @author chenxu
 * @since 2022/04/22 11:39
 */
@Slf4j
@Service
public class UserRegisterServiceImpl implements IRegisterService {

    @Autowired
    UserRegisterMapper registerMapper;
    @Autowired
    MemberMapper memberMapper;
    @Autowired
    MemberConverter memberConverter;
    @Autowired
    UserVerifyMapper verifyMapper;
    @Autowired
    private JavaMailSender javaMailSender;

    @Override
    public UserRegisterResponse register(UserRegisterRequest request) {
        //1.向用户表中插入一条记录
         UserRegisterResponse response = new UserRegisterResponse();

        try {
            //判空校验
            request.requestCheck();
            //判断用户名是否重复
            checkUsernameUnique(request);
            //密码加密处理
            String userpassword = DigestUtils.md5DigestAsHex(request.getUserPwd().getBytes());

            Member member = new Member();
            member.setUsername(request.getUserName());
            member.setEmail(request.getEmail());
            member.setCreated(new Date());
            member.setUpdated(new Date());
            member.setIsVerified("N");
            member.setState(1);
            member.setPassword(userpassword);

            int effectRows = memberMapper.insertSelective(member);
            if (effectRows != 1 ){
                response.setCode(UserRetCode.USER_REGISTER_FAILED.getCode());
                response.setMsg(UserRetCode.USER_REGISTER_FAILED.getMessage());
                return response;
            }
            //2.插入用户表成功，接下来就是插入用户认证表记录
            UserVerify userVerify = new UserVerify();
            //获取一个唯一的uuid
            String key = request.getUserName()+request.getUserPwd()+ UUID.randomUUID().toString();
            String uuid = DigestUtils.md5DigestAsHex(key.getBytes());

            userVerify.setUsername(request.getUserName());
            userVerify.setUuid(uuid);
            userVerify.setRegisterDate(new Date());
            userVerify.setIsExpire("N");
            userVerify.setIsVerify("N");

            int effectRows1 = verifyMapper.insert(userVerify);
            if (effectRows1 != 1 ){
                response.setCode(UserRetCode.USER_REGISTER_VERIFY_FAILED.getCode());
                response.setMsg(UserRetCode.USER_REGISTER_VERIFY_FAILED.getMessage());
                return response;
            }
            //3. 用户邮件激活
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom("893303593@qq.com");
            message.setTo(request.getEmail());
            message.setSubject("SM用户注册激活");
            StringBuffer stringBuffer = new StringBuffer();
            stringBuffer.append("http://localhost:9999/user/verify?uid=")
                    .append(uuid).append("&username=").append(request.getUserName());
            message.setText(stringBuffer.toString());
            javaMailSender.send(message);

            log.info("用户注册成功，注册的参数为requst:{}", JSON.toJSON(request));
            response.setCode(UserRetCode.SUCCESS.getCode());
            response.setMsg(UserRetCode.SUCCESS.getMessage());
        } catch (Exception e) {
            log.info("用户注册失败{}",e);
            ExceptionProcessorUtils.wrapperHandlerException(response,e);
        }
        return response;
    }

    private void checkUsernameUnique(UserRegisterRequest request) {
        Example example = new Example(Member.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("username",request.getUserName());
        List<Member> members = memberMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(members)){
            throw  new ValidateException(UserRetCode.USERNAME_ALREADY_EXISTS.getCode(),UserRetCode.USERNAME_ALREADY_EXISTS.getMessage());
        }
    }

}
